package com.abc.service.impl;

import com.abc.entity.User;
import com.abc.mapper.UserMapper;
import com.abc.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2024-12-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public boolean register(User user) throws Exception {
        // 验证用户名是否已存在
        User existUser = this.lambdaQuery().eq(User::getUserName, user.getUserName()).one();
        if (existUser != null) {
            throw new Exception("用户名已存在");
        }
        // 密码加密存储
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));
        return this.save(user);
    }

    @Override
    public boolean login(String userName, String password) throws Exception {
        User user = this.lambdaQuery().eq(User::getUserName, userName).one();
        if (user == null) {
            throw new Exception("用户不存在");
        }
        // 验证密码
        if (!DigestUtils.md5Hex(password).equals(user.getPassword())) {
            throw new Exception("密码错误");
        }
        return true;
    }

    @Override
    public boolean checkUser(Long userId) {
        User user = this.getById(userId);
        return user != null;
    }
}
